﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using QD.LopPlat.UI.Code.DbContent;
using QD.LopPlat.UI.Model.Sys;
using QD.Tools;

namespace QD.LopPlat.UI
{
    public partial class Sys_UidPwdMag : BaseForm
    {
        string operatestatus = "";
        DateTime defaultTime = new DateTime(1900, 1, 1);
        string _strState = "";
        private List<string> _qfCodeList = null;
        public Sys_UidPwdMag()
        {
            InitializeComponent();

            base.ToolsBtnAdd = this.toolStripButton4;
            base.ToolsBtnUpdate = this.ToolsBtnUpdate;
            base.ToolsBtnClose = this.toolStripButton2;

            this.grid_uid.InitGrid();
            this.grid_uid.RowTemplate.ContextMenuStrip = this.contextMenuStrip1;
        }

        private void Sys_UidPwdMag_Load(object sender, EventArgs e)
        {
            Bind_Db();
            Bind_Uid();
            DataTable dtSex = new DataTable();
            dtSex.Columns.Add("text", typeof(string));
            dtSex.Columns.Add("value", typeof(string));
            dtSex.Rows.Add("男", "0");
            dtSex.Rows.Add("女", "1");
            this.cbx_Sex.DataSource = dtSex;
            this.cbx_Sex.DisplayMember = "text";
            this.cbx_Sex.ValueMember = "value";
        }

        private void Bind_Uid()
        {
            this.Uid.ReadOnly = true;
            DbQfDevPlat db = new DbQfDevPlat();
            string sql = string.Format("select * from Sys_UidPwd");
            string strWhere = " where 1=1 ";

            string _key = this.txtKey.Text.Trim();
            if (!string.IsNullOrEmpty(_key))
            {
                strWhere += string.Format(" and (Uid like '%{0}%' or UserName like '%{0}%')", _key);
            }
            if (!string.IsNullOrEmpty(_strState))
            {
                strWhere += string.Format(" and (ForbidLogon = '{0}')", _strState);
            }
            DataTable dt = db.Query(sql + strWhere);

            this.grid_uid.DataSource = dt;


            //修正默认修中第一行的问题
            if (dt.Rows.Count > 0)
            {
                this.grid_uid.Rows[0].Selected = false;
            }
        }

        /// <summary>
        /// 根据用户编号绑定组织
        /// </summary>
        /// <param name="uid"></param>
        private void Bind_Db(string uid = "")
        {
            _qfCodeList = new List<string>();
            DbQfDevPlat db = new DbQfDevPlat();
            DataTable dtOrg = db.Query("select 0 as ID,QfCode,QfName from QDDataBase");
            if (dtOrg != null && dtOrg.Rows.Count > 0 && uid != "")
            {
                DataTable dt = db.Query("select QfCode from Sys_UidRefQf where Uid='" + uid + "'");
                if (dt != null)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        string code = dr["QfCode"].ToString();
                        foreach (DataRow item in dtOrg.Rows)
                        {
                            string qfCode = item["QfCode"].ToString();
                            if (code == qfCode)
                            {
                                item["ID"] = true;
                                _qfCodeList.Add(qfCode);
                            }
                        }
                    }
                }
            }
            this.dataGridView1.DataSource = dtOrg;

        }

        private void txtKey_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Bind_Uid();
                Bind_Db();
            }
        }

        private void grid_uid_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex != -1)
            {
                string uid = this.grid_uid.Rows[e.RowIndex].Cells["ListUid"].Value.ToString();
                InitUIData(uid);
            }
        }

        protected override void InitUIData(string uid)
        {
            DbQfDevPlat dbPlat = new DbQfDevPlat();
            Sys_UidPwd user = dbPlat.Sys_UidPwd.First(p => p.Uid == uid);
            if (user != null)
            {
                Bind_Db(uid);
                operatestatus = "";
                this.Uid.ReadOnly = true;
                this.Uid.Text = user.Uid;
                this.UserName.Text = user.UserName;
                this.ForbidLogon.Checked = user.ForbidLogon;
                this.IsLoginService.Checked = user.IsLoginService;
                this.Mobile.Text = user.Mobile;
                this.txtIDCard.Text = user.IDCard;
                if (user.Sex != null)
                {
                    this.cbx_Sex.SelectedIndex = Convert.ToInt32(user.Sex);
                }
                else
                {
                    this.cbx_Sex.SelectedIndex = -1;
                }
                this.Birthday.Value = user.Birthday == null ? defaultTime : Convert.ToDateTime(user.Birthday);
                //this.txtPwd.Text = user.Pwd;
                //this.txtAPwd.Text = user.Pwd;
                this.txtPwd.Enabled = false;
                this.txtAPwd.Enabled = false;
            }
            else
            {
                Tools.PromptHelper.Prompt("用户 [" + uid + "] 不存在或已经被删除！");
            }
            base.InitUIData(uid);
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void ToolsBtnAdd_Click(object sender, EventArgs e)
        {
            Bind_Db();
            operatestatus = "new";
            this.Uid.Text = "";
            this.Uid.ReadOnly = false;
            this.UserName.Text = "";
            this.Mobile.Text = "";
            this.txtIDCard.Text = "";
            this.cbx_Sex.SelectedIndex = 0;
            this.Birthday.Value = defaultTime;
            this.txtPwd.Enabled = true;
            this.txtAPwd.Enabled = true;
            this.txtPwd.Text = "";
            this.txtAPwd.Text = "";
        }
        protected override void ToolsBtnUpdate_Click(object sender, EventArgs e)
        {

            try
            {
                DbQfDevPlat dbPlat = new DbQfDevPlat();

                //用户只能修改，不能新增
                string uid = this.Uid.Text.Trim();
                string username = this.UserName.Text.Trim();
                string mobile = this.Mobile.Text.Trim();
                string idCard = this.txtIDCard.Text.Trim();

                int sex = -1;
                if (this.cbx_Sex.SelectedIndex != -1)
                {
                    sex = int.Parse(this.cbx_Sex.SelectedValue.ToString());
                }
                DateTime? birthday = this.Birthday.Value;
                if (birthday == defaultTime)
                {
                    birthday = null;
                }

                if (string.IsNullOrEmpty(uid))
                {
                    PromptHelper.Prompt("用户号不能为空！");
                    this.Uid.Focus();
                    return;
                }
                else if (string.IsNullOrEmpty(username))
                {
                    PromptHelper.Prompt("用户名不能为空！");
                    this.UserName.Focus();
                    return;
                }
                else if (!string.IsNullOrEmpty(idCard) && idCard.Length != 18)
                {
                    PromptHelper.Prompt("身份证不合法！");
                    this.txtIDCard.Focus();
                    return;
                }
                if (this.cbx_Sex.SelectedIndex == -1)
                {
                    PromptHelper.Prompt("请选择性别！");
                    this.cbx_Sex.Focus();
                    return;
                }

                if (operatestatus == "new")//新增
                {
                    string pwd = this.txtPwd.Text.Trim();
                    string apwd = this.txtAPwd.Text.Trim();
                    if (string.IsNullOrEmpty(pwd))
                    {
                        PromptHelper.Prompt("请输入密码！");
                        this.txtPwd.Focus();
                        return;
                    }
                    else if (pwd != apwd)
                    {
                        PromptHelper.Prompt("两次输入的密码不相同！");
                        this.txtPwd.Focus();
                        return;
                    }
                    else if (dbPlat.Sys_UidPwd.Any(p => p.Uid == uid))
                    {
                        PromptHelper.Prompt("帐号已存在！");
                        return;
                    }
                    else if (!string.IsNullOrEmpty(idCard))
                    {
                        if (dbPlat.Sys_UidPwd.Any(p => p.IDCard == idCard))
                        {
                            PromptHelper.Prompt("身份证已存在！");
                            return;
                        }
                    }
                    else if (!string.IsNullOrEmpty(mobile))
                    {
                        if (dbPlat.Sys_UidPwd.Any(p => p.Mobile == mobile))
                        {
                            PromptHelper.Prompt("手机号已存在！");
                            return;
                        }
                    }
                    Sys_UidPwd mod = new Sys_UidPwd();
                    mod.Uid = uid;
                    mod.UserName = username;
                    mod.Pwd = pwd.ToMD5Encryption();
                    mod.Sex = sex;
                    mod.ForbidLogon = this.ForbidLogon.Checked; 
                    mod.IsLoginService = this.IsLoginService.Checked;
                    mod.Birthday = birthday;
                    mod.IDCard = idCard;
                    mod.Mobile = mobile;
                    mod.CreateDate = DateTime.Now;
                    dbPlat.Sys_UidPwd.Add(mod);
                    dbPlat.SaveChanges();
                    operatestatus = "";

                }
                else//修改
                {
                    if (string.IsNullOrEmpty(uid))
                    {
                        PromptHelper.Prompt("用户号不能为空！");
                    }
                    else if (string.IsNullOrEmpty(username))
                    {
                        PromptHelper.Prompt("用户名不能为空！");
                    }
                    else
                    {
                        Sys_UidPwd user = dbPlat.Sys_UidPwd.First(p => p.Uid == uid);
                        if (user != null)
                        {
                            user.UserName = username;
                            user.ForbidLogon = this.ForbidLogon.Checked;
                            user.IsLoginService = this.IsLoginService.Checked;
                            user.Mobile = mobile;
                            user.Sex = sex;
                            user.Birthday = birthday;
                            user.IDCard = idCard;
                            dbPlat.SaveChanges();
                        }
                        else
                        {
                            Tools.PromptHelper.Prompt("用户 [" + uid + "] 不存在或已经被删除！");
                        }
                    }
                }

                SaveOrg(dbPlat, uid);

                this.Uid.ReadOnly = true;
                PromptHelper.Prompt("保存成功！");
                InitUIData(uid);
                Bind_Uid();
                Bind_Db(uid);

            }
            catch (Exception ex)
            {
                Tools.PromptHelper.Prompt(ex);
            }
        }
        /// <summary>
        /// 保存我的组织
        /// </summary>
        private void SaveOrg(DbQfDevPlat dbPlat, string uid)
        {
            dataGridView1.EndEditState();
            List<string> newQfCodeList = new List<string>();
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                bool id = dataGridView1.Rows[i].Cells[0].Value.ToString() == "1" ? true : false;
                string qfCode = dataGridView1.Rows[i].Cells[1].Value.ToString();
                if (id)
                {
                    newQfCodeList.Add(qfCode);
                }

            }
            List<string> addQfCodeList = new List<string>();
            foreach (var item in newQfCodeList)
            {
                var t = _qfCodeList.FirstOrDefault(x => x == item);
                if (t == null)
                {
                    addQfCodeList.Add(item);
                }
            }

            List<string> delQfCodeList = new List<string>();
            foreach (var item in _qfCodeList)
            {
                var t = newQfCodeList.FirstOrDefault(x => x == item);

                if (t == null)
                {
                    delQfCodeList.Add("'" + item + "'");
                }
            }
            string delQfCodes = string.Join(",", delQfCodeList);
            if (!string.IsNullOrEmpty(delQfCodes))
            {
                string sql = string.Format("delete Sys_UidRefQf where Uid='{0}' and QfCode in ({1})", uid, delQfCodes);
                dbPlat.ExecuteNonQuery(sql);
            }

            foreach (var item in addQfCodeList)
            {
                Sys_UidRefQf mod = new Sys_UidRefQf();
                mod.QfCode = item;
                mod.Uid = uid;
                mod.IsEnableDesign = false;
                mod.CreateDate = DateTime.Now;
                dbPlat.Sys_UidRefQf.Add(mod);
            }
            dbPlat.SaveChanges();
        }
        /// <summary>
        /// 全部
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAll_Click(object sender, EventArgs e)
        {
            _strState = "";
            Bind_Uid();
        }
        /// <summary>
        /// 允许登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAllow_Click(object sender, EventArgs e)
        {
            _strState = "0";
            Bind_Uid();
        }
        /// <summary>
        /// 禁止登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnForbid_Click(object sender, EventArgs e)
        {
            _strState = "1";
            Bind_Uid();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (PromptHelper.PromptOkCancel("您确认删除所有选中用户？") == DialogResult.OK)
            {
                try
                {
                    IList<DataGridViewRow> rows = this.grid_uid.GetSelectRows();

                    if (rows.Count == 0)
                    {
                        throw new Exception("你未选择任何需要删除的用户！");
                    }
                    else
                    {
                        DbQfDevPlat dbPlat = new DbQfDevPlat();
                        foreach (DataGridViewRow row in rows)
                        {
                            string uid = row.Cells["ListUid"].Value.ToString();

                            string sql = string.Format(@"delete from Sys_UidPwd where uid='{0}'
delete from Sys_UidRefQf where uid='{0}'
delete from Sys_UidRoleRel where uid='{0}'
delete from Sys_UserRolePernLog where uid='{0}'
delete from Sys_UidWorkWX where uid='{0}'", uid);

                            dbPlat.Database.ExecuteSqlCommand(sql);
                        }

                        Bind_Uid();

                        PromptHelper.Prompt("删除成功！");
                    }
                }
                catch (Exception ex)
                {
                    PromptHelper.Prompt(ex);
                }
            }
        }

        private void 复制单元格ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.grid_uid.CopyFirstSelectedCellValue();
        }

        private void 复制所有选中单元格ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.grid_uid.CopySelectedCellsValue();
        }
    }
}
